<script setup lang="ts">
import { ref, watch, onMounted, computed } from 'vue'
import { ElSelect, ElOption, ElMessage } from 'element-plus'
import materialApi from '../api/material.js'

// 定义props
const props = defineProps<{
  modelValue: string | number | null
  placeholder?: string
  disabled?: boolean
  filterable?: boolean
}>()

// 定义emits
const emit = defineEmits<{
  (e: 'update:modelValue', value: string | null): void
  (e: 'change', value: string | null): void
}>()

// 组件内部状态
const currentValue = ref<string | null>(null)
const materials = ref([])
const loading = ref(false)
const searchQuery = ref('')
const filteredMaterials = ref([])

// 监听modelValue变化
watch(
  () => props.modelValue,
  (newValue) => {
    currentValue.value = newValue || ''
  },
  { immediate: true }
)

// 监听currentValue变化，触发update:modelValue事件
watch(
  currentValue,
  (newValue) => {
    emit('update:modelValue', newValue)
    emit('change', newValue)
  }
)

// 获取物料列表
const fetchMaterials = async () => {
  loading.value = true
  try {
    // 使用materialApi获取物料数据
    const response = await materialApi.getAll()
    materials.value = response?.items || response || []
    filterMaterials()
  } catch (error) {
    console.error('Failed to fetch materials:', error)
    ElMessage.error('获取物料数据失败')
  } finally {
    loading.value = false
  }
}

// 过滤物料
const filterMaterials = () => {
  if (!searchQuery.value) {
    filteredMaterials.value = materials.value
    return
  }

  const query = searchQuery.value.toLowerCase()
  filteredMaterials.value = materials.value.filter(material => {
    // 适配API返回的数据结构
    const materialName = material.MaterialName?.toLowerCase() || material.materialName?.toLowerCase() || ''
    const specification = material.Specification?.toLowerCase() || material.specification?.toLowerCase() || ''
    const materialCode = material.MaterialCode?.toLowerCase() || material.materialCode?.toLowerCase() || ''
    return materialName.includes(query) || specification.includes(query) || materialCode.includes(query)
  })
}

// 监听搜索查询变化
watch(searchQuery, filterMaterials)

// 组件挂载时加载物料
onMounted(() => {
  fetchMaterials()
})
</script>

<template>
  <ElSelect
    v-model="currentValue"
    :placeholder="placeholder || '请选择物料'"
    :disabled="disabled"
    filterable
    :remote-method="(query) => { searchQuery.value = query }"
    :loading="loading"
    style="width: 100%"
    @change="(value) => emit('change', value)"
  >
    <ElOption
      v-for="material in filteredMaterials"
      :key="material.id || material.Id"
      :label="`${material.MaterialName || material.materialName || ''} (${material.Specification || material.specification || ''})`"
      :value="(material.id || material.Id)?.toString() || ''"
    />
  </ElSelect>
</template>